
<template>
  <div>
    <page :asideShow="asideShow">

      <div slot="content">
        <div class="wrap">
          <p class="title">基本资料：</p>
          <el-form
            ref="form"
            :model="form"
            style="width: 80%;"
            label-width="120px"
            :rules="formRules"
          >
            <el-form-item label="姓名" prop="name">
              <el-input v-model="form.name" clearable></el-input>
            </el-form-item>

            <el-form-item label="证件号" prop="idCard">
              <el-input v-model="form.idCard" clearable></el-input>
            </el-form-item>

            <el-form-item label="手机号" prop="phone">
              <el-input v-model="form.phone" type="number" clearable></el-input>
            </el-form-item>
            <el-form-item label="民族" prop="nation">
              <el-input v-model="form.nation" clearable></el-input>
            </el-form-item>

            <el-form-item label="人员类型" prop="type">
              <el-select v-model="form.type" placeholder="请选择" clearable>
                <el-option
                  v-for="item in houseList"
                  :key="item.DID"
                  :label="item.name"
                  :value="item.DID"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="选择小区" prop="CID">
              <el-select v-model="form.CID" placeholder="请选择" clearable>
                <el-option
                  v-for="item in villageList"
                  :key="item._id"
                  :label="item.name"
                  :value="item.CID"
                ></el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="出生日期">
              <el-date-picker v-model="form.birthday" type="date" placeholder="选择日期" clearable></el-date-picker>
            </el-form-item>
            <el-form-item label="学历">
              <el-input v-model="form.educationType" clearable></el-input>
            </el-form-item>
            <el-form-item label="人户一致">
              <el-radio v-model="form.unConsistency" label="0">否</el-radio>
              <el-radio v-model="form.unConsistency" label="1">是</el-radio>
            </el-form-item>
            <el-form-item label="婚姻状态">
              <el-radio v-model="form.maritalStatus" label="0">未婚</el-radio>
              <el-radio v-model="form.maritalStatus" label="1">已婚</el-radio>
            </el-form-item>

            <el-form-item label="是否预警">
              <el-radio v-model="form.earlyWarning" label="0">不预警</el-radio>
              <el-radio v-model="form.earlyWarning" label="1">预警</el-radio>
            </el-form-item>

            <el-form-item label="上传头像">
              <el-upload
              :action="imageSrc"
              list-type="picture-card"
                :multiple="true"
                
              :on-preview="handlePreview"
              :on-remove="handleRemove">
              <i class="el-icon-plus"></i>
            </el-upload>
              <!-- <el-upload
                ref="uploadImg"
                class="avatar-uploader"
                action="#"
                :show-file-list="false"
                :multiple="true"
                :on-preview="handlePictureCardPreview"
                :http-request="upLoad"
              >
                <img v-if="this.form.photo" :src="getItemPhoto(this.form.photo)" class="avatar" />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload> -->
              
<el-upload 
        ref="upload"
		accept=".txt"		
       action="http://192.168.1.111:8000/capabilitylayer/uploadFile/:xqid"                      
		:before-upload="beforeUpload"     
     :on-preview="handlePreview" 
     :on-success ="hangdlesucess"    

       :auto-upload="false"   
           
		>
    <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
  <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>
  <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
<el-button type="primary" :disabled="this.fileList.length !== 0">上传文件</el-button>
</el-upload>
 


              <span style="color:red">*头像必须上传</span>
            </el-form-item>

            <el-form-item style="width:100%;text-align:center">
              <el-button type="primary" @click="onSubmit">立即创建</el-button>
              <el-button @click="cancelSubmit('form')">取消</el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>

      <!-- <div slot="footer">
          <el-pagination
            layout="total, prev, pager, next, jumper"
            @current-change="refreshPageRequest"
            :current-page="pageRequest.page"
            :page-size="pageRequest.pageSize"
            :total="totalSize"
            style="float:right;"
          ></el-pagination>
      </div>-->
    </page>
  </div>
</template>
  
  <script>
export default {
  data() {
    // 验证手机号的规则
    var checkMobile = (rule, value, cb) => {
      const regMobile = /^^1[0-9]{10}$/;
      if (regMobile.test(value)) {
        return cb();
      }
      cb(new Error("请输入合法的手机号"));
    };
    return {
      fileList:[],
      asideShow: false,
      unitShow: false,
      imageSrc:'http://192.168.1.111:8000/admin/api/upload1/',
      pageRequest: {
        page: 1,
        pageSize: 10
      },
      form: {
        CID: "",
        name: "", //名称
        idCard: "", //身份证号
        nation: "", //民族
        nationality: "", //国籍
        political: "", // 政治面貌
        type: "", //  人员类型
        birthday: "", // 出生年月日
        auditType: "", // 审核状态 类型表
        unConsistency: "", // 人户一致
        maritalStatus: "",
        earlyWarning: "", //是否预警
        educationType: "", // 学历
        photo: "", // 图片表
        status: "" // 是否删除
      },
      formRules: {
        name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
        idCard: [
          { required: true, message: "请输入身份证号码", trigger: "blur" }
        ],

        nation: [{ required: true, message: "请输入民族", trigger: "blur" }],
        phone: [
          { required: true, message: "请输入手机号码", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" }
        ],

        type: [{ required: true, message: "人员类型必填", trigger: "blur" }],
        CID: [{ required: true, message: "小区必选", trigger: "blur" }]
      },
      houseList: [],
      personList: [],
      // 添加上传图片
      imageUrl: "",
      // 上传图片
      dialogImageUrl: "",
      dialogVisible: false,
      // 小区列表
      villageList: []
    };
  },
  created() {
    this.getCommunityList();
    let dictData = sessionStorage.getItem("dictData");
    let dictList = JSON.parse(dictData);
    this.houseList = dictList.sys_person_type;
  },
  beforeCreate() {
			// 读取文件
			FileReader.prototype.reading = function ({encode} = pms) {
				let bytes = new Uint8Array(this.result);    //无符号整型数组
				let text = new TextDecoder(encode || 'UTF-8').decode(bytes);
				return text;
			};
			/* 重写readAsBinaryString函数 */
			FileReader.prototype.readAsBinaryString = function (f) {
				if (!this.onload)       //如果this未重写onload函数，则创建一个公共处理方式
					this.onload = e => {  //在this.onload函数中，完成公共处理
						let rs = this.reading();
						console.log(rs);
					};
				this.readAsArrayBuffer(f);  //内部会回调this.onload方法
      };
  },


  methods: {
    hangdlesucess(f,d,g){
    },
    submitUpload() {
        this.$refs.upload.submit();
      },
      handleRemove(file, fileList) {
        console.log(file, fileList);
      },
      handlePreview(file,d) {
        console.log(file);
      },

    
     beforeUpload(file){
        this.fileList = [file]
        
        console.log('选择了文件beforeUpload');
        console.log(file);
        // 读取数据
        this.read(file);
        
        return false
    },
    read(f) {

      

			let rd = new FileReader();
			rd.onload = e => {  
            //this.readAsArrayBuffer函数内，会回调this.onload函数。在这里处理结果
        let cont = rd.reading({encode: 'utf-8'});
        
        let data = JSON.parse(cont)
        console.log(data);
        
				let  formerData = this.textData;
				this.textData = formerData + "\n" + cont;
			};
			rd.readAsBinaryString(f);
	},

    //图片处理
    getBase64(file) {
      return new Promise(function(resolve, reject) {
        let reader = new FileReader();
        let imgResult = "";
        reader.readAsDataURL(file);
        reader.onload = function() {
          imgResult = reader.result;
        };
        reader.onerror = function(error) {
          reject(error);
        };
        reader.onloadend = function() {
          resolve(imgResult);
        };
      });
    },

    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    // 上传图片
    async upLoad(param) {
      var imgup = "";
      await this.getBase64(param.file).then(res => {
        imgup = res;
      });
      var paramd = {
        img: imgup
      };
      var snn = JSON.stringify(paramd);
      this.$api.imgAdd
        .addimgPer(paramd)
        .then(res => {
          this.form.photo = res.id;
        })
        .catch(err => {
          console.log("上传失败", err);
        });
    },
    // 拼接图片
    getItemPhoto(id) {
      var url = this.$ports.imgURL + this.$ports.avatars + id;
      return url;
    },
    // 添加人员
    onSubmit(formRest) {
      // this.form.photo = this.imageUrl;
      var params = this.form;
      let paramJson = JSON.stringify(params);
      this.$api.PlatformEntry.personAdd(paramJson).then(res => {
        if (res.code == 0) {
          this.$message({
            type: "success",
            message: "添加成功"
          });
          this.$refs["form"].resetFields();
          this.$refs.uploadImg.clearFiles();
        } else {
          this.$message({
            type: "info",
            message: "添加失败"
          });
        }
      });
    },

    getCommunityList() {
      this.$api.build.communityList().then(res => {
        if (res.code == 0) {
          this.villageList = res.data;
        }
      });
    },
    cancelSubmit() {}
  }
};
</script>
  
  <style lang="scss" scoped>
.wrap {
  width: 100%;
  height: 100%;
  padding: 50px;
  box-sizing: border-box;
  background: #fff;
}
.el-upload-list {
  position: absolute;
  z-index: 99px;
}
.el-form-item__content {
  .el-cascader {
    width: 100%;
  }
  .el-select {
    width: 100%;
  }
}

.title {
  margin-bottom: 20px;
}
.el-collapse-item__arrow {
  margin: 0;
}
.el-form {
  margin: 0 auto;
  display: flex;
  width: 100%;
  flex-wrap: wrap;
  justify-content: space-between;
}

.el-form-item {
  width: 45%;
}
.el-date-editor.el-input,
.el-date-editor.el-input__inner {
  width: 101%;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9 !important;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 150px;
  height: 150px;
  line-height: 150px;
  text-align: center;
}
.avatar {
  width: 150px;
  height: 150px;
  display: block;
}
</style>